/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * 
 * Project Name:assign-tracer
 * Create Time: 2016年2月2日 下午1:13:23
 */
package com.lenovo.lmrp.server.assigntracer.domain.engineer;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lenovo.lmrp.api.constant.EngineerState;
import com.lenovo.lmrp.api.constant.MessageTemplateType;
import com.lenovo.lmrp.api.model.entity.EngineerPO;
import com.lenovo.lmrp.api.model.entity.EngineerTerminalPO;
import com.lenovo.lmrp.api.model.entity.MessageTemplatePO;
import com.lenovo.lmrp.api.model.view.EngineerVO;
import com.lenovo.lmrp.api.model.view.LoginData;
import com.lenovo.lmrp.base.mq.MQContent;
import com.lenovo.lmrp.server.assigntracer.domain.service.QuerySelector;
import com.lenovo.lmrp.server.assigntracer.events.AppGatewayHandle;
import com.lenovo.lmrp.server.assigntracer.util.pusher.SenderUtil;
import com.lenovo.lmrp.server.assigntracer.util.pusher.TransformUtil;
import com.lenovo.sdc.framework.dao.ADaoFactory;
import com.lenovo.sdc.framework.dao.ICommonDAO;
import com.lenovo.sdc.framework.util.EncryptUtil;
import com.lenovo.sdc.framework.util.JSONHelper;
import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;

/**
 * 
 * @author songyz
 * @version v1.0
 */
public class EngineerBO {
    private final static Logger logger = LoggerFactory.getLogger(EngineerBO.class);
    private String itsmCode;
    private EngineerPO po;

    public EngineerBO(String itsmCode, EngineerPO po) {
        this.itsmCode = itsmCode;
        this.po = po;
    }

    /**
     * 判断是否是新设备登录
     * 
     * @param terminal
     * @return
     */
    public boolean traceLogin(EngineerTerminalPO terminal) {
        boolean isNew = false;
        // iterate engineer terminal list to update status
        List<EngineerTerminalPO> terminals = po.getTerminals();
        boolean notFound = true;
        for (EngineerTerminalPO item : terminals) {
            if (item.getEngineerid().equals(terminal.getEngineerid())
                && item.getTerminalid().equals(terminal.getTerminalid())) {
                // change status to online
                item.setStatus(EngineerState.ONLINE.getState());
                item.setUpdatetime(new Date());

                terminal.setUpdatetime(new Date());
                terminal.setId(item.getId());
                terminal.setStatus(EngineerState.ONLINE.getState());
                notFound = false;
                break;
            }
            else {
                // do we nee to set other terminal offline?, if so change other
                // terminal status to offline
            }
        }

        // if terminial is new, set ID and put to list
        if (notFound) {
            terminal.setId(EncryptUtil.getUUID());
            terminal.setUpdatetime(new Date());
            terminal.setStatus(EngineerState.ONLINE.getState());
            po.getTerminals().add(terminal);
            isNew = true;
        }
        return isNew;
    }

    /**
     * 登出
     * 
     * @param terminal
     */
    public void traceLoginOut(EngineerTerminalPO terminal) {
        //		List<EngineerTerminalPO> filteByConditionList = QuerySelector.getEngineerTerminalPOList(itsmCode,
        //				new RecordFilter().addCondition(new Condition<String, Object>("engineerid", terminal.getEngineerid()))
        //						.addCondition(new Condition<String, Object>("terminalid", terminal.getTerminalid()),
        //								RelationEnum.AND)
        //						.addCondition(new Condition<String, Object>("cid", terminal.getCid()), RelationEnum.AND));
        try (ICommonDAO dao = ADaoFactory.getDefault().createDAO(itsmCode)) {
            dao.beginTrans();
            String hql = "update EngineerTerminalPO set status = ?,updatetime = ? "
                         + " where engineerid = ? and terminalid = ? and cid = ?";
            dao.executeHQL(hql, new Object[] { EngineerState.OFFLINE.getState(), new Date(), terminal.getEngineerid(),
                                              terminal.getTerminalid(), terminal.getCid() });
            dao.endTrans();
            //			for (EngineerTerminalPO engineerTerminalPO : filteByConditionList) {
            //				engineerTerminalPO.setStatus(EngineerState.OFFLINE.getState());
            //				engineerTerminalPO.setUpdatetime(new Date());
            //				dao.beginTrans();
            //				dao.update(engineerTerminalPO);
            //				dao.endTrans();
            if (logger.isDebugEnabled())
                logger.debug("Logout success ,engineerId:{},cid:{}", terminal.getEngineerid(), terminal.getCid());
            //			}
        }
        catch (Exception e) {
            throw new TraceableException(ErrorCode.DB_UPDATE_FAILED, e);
        }
    }

    /**
     * 强制登出
     * 
     * @param content
     */
    public void forceLogOut(MQContent mqContent) {
        LoginData loginData = null;
        EngineerPO engineerPO = null;
        try {
            loginData = JSONHelper.fromJSON(JSONHelper.toJSON(mqContent.getContent()), LoginData.class);
        }
        catch (Exception e) {
            throw new TraceableException(ErrorCode.COMM_PARSE_FAILED, e);
        }
        // 登出
        traceLoginOut(AppGatewayHandle.transformEngineerTerminalPO(mqContent));

        EngineerVO engineerVO = TransformUtil.tranEngineerPO2VO(engineerPO);
        engineerVO.setItsmcode(itsmCode);
        // cid是mq传过来的
        engineerVO.setEngineerOnLineCids(loginData.getCid());
        // 查询消息模板
        List<MessageTemplatePO> messageTemplateList = new QuerySelector().getMessageTemplateList(itsmCode,
            MessageTemplateType.LOGOUT);
        SenderUtil.sendMessageCreateCache(engineerVO, messageTemplateList);
    }
}
